//
//  YKPhotosView.m
//  youkan
//
//  Created by 吴高烽 on 16/3/13.
//  Copyright © 2016年 Honsintech. All rights reserved.
//

#import "YKPhotosView.h"
#import "UIImageView+WebCache.h"
#import "YKPhoto.h"
#import "YKPhotoView.h"
#import "MJPhotoBrowser.h"
#import "MJPhoto.h"
@implementation YKPhotosView
-(instancetype)initWithFrame:(CGRect)frame{
    if (self =[super initWithFrame:frame]) {
//        self.backgroundColor =[UIColor redColor];
          [self setUpAllChildView];
    }
    return self;
}
-(void)setUpAllChildView{
    for (int i=0; i<9; i++) {
        YKPhotoView *imageV =[[YKPhotoView alloc]init];
        imageV.tag=i;
        UITapGestureRecognizer *tapG=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
        [imageV addGestureRecognizer:tapG];
        
        [self addSubview:imageV];
    }
}
// imageView的点击事件
-(void)tap:(UITapGestureRecognizer*)tap{
    YKPhotoView *imageV=(YKPhotoView*)tap.view;
    NSMutableArray *mArr=[NSMutableArray array];
    for (int i=0; i<_pic_urls.count; i++) {
        YKPhoto *photo =_pic_urls[i];
        MJPhoto *ph=[[MJPhoto alloc]init];
        NSString *urlStr=photo.thumbnail_pic.absoluteString;
        urlStr = [urlStr stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
        ph.url =[NSURL URLWithString:urlStr];
        ph.index =i;
        ph.srcImageView=imageV;
        [mArr addObject:ph];
    }
    // 弹出图片浏览器
    // 创建浏览器对象
    MJPhotoBrowser *brower = [[MJPhotoBrowser alloc] init];
    // MJPhoto
    brower.photos =mArr;
    brower.currentPhotoIndex =imageV.tag;
    [brower show];
}
//该方法会循环利用（多次调用）
-(void)setPic_urls:(NSArray *)pic_urls{
    _pic_urls =pic_urls;
    NSInteger count =self.subviews.count;
    for (int i=0; i<count; i++) {
        YKPhotoView *imageV =self.subviews[i];
        if (i<pic_urls.count) {
            YKPhoto *photo=_pic_urls[i];
            imageV.photo =photo;
            imageV.hidden =NO;
            [imageV sd_setImageWithURL:photo.thumbnail_pic placeholderImage:[UIImage imageNamed:@"timeline_image_placeholder"]];
            if (imageV.image.size.height>imageV.image.size.width*3) {
                YKLog(@"长图");
            }
        }else{
            imageV.hidden =YES;
        }
    }

}
-(void)layoutSubviews{
    [super layoutSubviews];
    CGFloat x=0;
    CGFloat y=0;
    CGFloat wh =70;
    NSInteger col =0;
    NSInteger rol =0;
    NSInteger cols=_pic_urls.count==4?2:3;
    for (int i=0; i<_pic_urls.count; i++) {
        YKPhotoView *imageV=self.subviews[i];
        col =i%cols;
        rol =i/cols;
        x=col*(wh+YKStatusCellMargin);
        y=rol *(wh+YKStatusCellMargin);
        imageV.frame =CGRectMake(x, y, wh, wh);
    }
}
@end
